package com.liuhouse.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.liuhouse.enums.AppHttpCodeEnum;
import com.liuhouse.exception.SystemException;
import com.liuhouse.pojo.User;
import com.liuhouse.mapper.UserMapper;
import com.liuhouse.pojo.UserRole;
import com.liuhouse.service.IUserRoleService;
import com.liuhouse.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liuhouse.utils.BeanCopyUtils;
import com.liuhouse.utils.ResponseResult;
import com.liuhouse.utils.SecurityUtils;
import com.liuhouse.vo.PageVo;
import com.liuhouse.vo.UserInfoVo;
import com.liuhouse.vo.UserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author liuhouse
 * @since 2024-01-27
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    //解密和加密用这套算法,我们在liuhouse-blog工程的securityConfig类里面覆盖过PasswordEncoder
    private PasswordEncoder passwordEncoder;


    @Autowired
    private IUserRoleService userRoleService;

    //查询个人信息
    @Override
    public ResponseResult userInfo() {
        //获取当前登录用户的id , SecurityUtils是我们在liuhouse-framework工程写的类
        Long userId = SecurityUtils.getUserId();
        //根据用户id查询用户信息
        User user = getById(userId);
        //封装成UserInfoVo
        UserInfoVo vo = BeanCopyUtils.copyBean(user, UserInfoVo.class);
        return ResponseResult.okResult(vo);
    }

    @Override
    public ResponseResult updateUserInfo(User user) {
        //updateById是mybatisPlus提供的方法  根据id更新信息
        updateById(user);
        return ResponseResult.okResult();
    }

    //用户进行注册
    @Override
    public ResponseResult register(User user) {
        this.validateUser(user);
        //经过上面的判断,可以确保用户传给我们的用户名和昵称在数据库中是不存在的,且相关字段都不为空
        //就可以存入数据库
        //注意用户传给我们的密码是明文，对于密码,我们要先转成密文之后再存入数据库,注意要加密和解密要用同一套算法
        //在liuhouse-blog工程里面的securityConfig类里面有解密算法,当时我们写了一个passwordEncoder的方法,并且已经
        //注入到spring容器中
        String encodePassword = passwordEncoder.encode(user.getPassword());//将密码加密
        //将加密后的密码设置到用户对象中
        user.setPassword(encodePassword);
        //存入数据库,save方法是mybatisPlus提供的方法
        save(user);
        //封装响应返回
        return ResponseResult.okResult();
    }


    //查询用户列表
    @Override
    public ResponseResult selectUserPage(User user, Integer pageNum, Integer pageSize) {
        //构建查询条件
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        //如果条件中有用户名称的话,那么就使用模糊查询
        queryWrapper.like(StringUtils.hasText(user.getUserName()) , User::getUserName , user.getUserName());
        //状态筛查
        queryWrapper.eq(StringUtils.hasText(user.getStatus()) , User::getStatus , user.getStatus());
        //电话号码查询
        queryWrapper.eq(StringUtils.hasText(user.getPhonenumber()) , User::getPhonenumber , user.getPhonenumber());

        //进行分页设置
        Page<User> page = new Page<>();
        page.setCurrent(pageNum);
        page.setSize(pageSize);
        //查询分页数据
        page(page , queryWrapper);

        //转换成Vo进行返回
        List<User> users = page.getRecords();
        long total = page.getTotal();
        List<UserVo> userVoList = BeanCopyUtils.copyBeanList(users, UserVo.class);
        //构建分页数据
        PageVo pageVo = new PageVo(userVoList , total);
        return ResponseResult.okResult(pageVo);
    }

    @Override
    public boolean checkUserNameUnique(String userName) {
        LambdaQueryWrapper<User> wrapper = Wrappers.<User>lambdaQuery().eq(User::getUserName, userName);
        long count = count(wrapper);
        return count == 0;
    }

    @Override
    public boolean checkPhoneUnique(User user) {
        //使用Wrappers工具类的时候 要在前面定义好要操作的对象
        return count(Wrappers.<User>lambdaQuery().eq(User::getPhonenumber , user.getPhonenumber())) == 0;
    }

    @Override
    public boolean checkEmailUnique(User user) {
        return count(Wrappers.<User>lambdaQuery().eq(User::getEmail , user.getEmail())) == 0;
    }

    //添加用户
    @Transactional
    @Override
    public ResponseResult addUser(User user) {
        //密码进行加密处理
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        this.save(user);
        //判断是否给用户选择了角色,如果角色存在,就要添加角色
        if(user.getRoleIds() != null && user.getRoleIds().length > 0){
            //给用户添加角色
            insertUserRole(user);
        }
        return ResponseResult.okResult();
    }



    //给用户添加角色
    private void insertUserRole(User user) {
        List<UserRole> userRoleList = Arrays.stream(user.getRoleIds())
                .map(roleId -> new UserRole(user.getId(), roleId))
                .collect(Collectors.toList());
        userRoleService.saveBatch(userRoleList);
    }

    //更新用户信息
    @Override
    @Transactional
    public void updateUser(User user) {
        //1删除用户和角色的关联
        LambdaQueryWrapper<UserRole> userRoleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //通过用户id查询对应的关联的角色信息
        userRoleLambdaQueryWrapper.eq(UserRole::getUserId , user.getId());
        userRoleService.remove(userRoleLambdaQueryWrapper);
        //2添加用户和角色的关联
        //如果选中了角色的时候才需要进行添加角色
        if(user.getRoleIds().length > 0 && user.getRoleIds() != null){
            insertUserRole(user);
        }
        //3.更新用户信息
        this.updateById(user);
    }


    private void validateUser(User user) {
        //对前端传递过来的用户名进行非空判断,例如null , "",就抛出异常
        //用户名不能为空
        if(!StringUtils.hasText(user.getUserName())){
            throw new SystemException(AppHttpCodeEnum.USERNAME_NOT_NULL);
        }
        //密码不能为空
        if(!StringUtils.hasText(user.getPassword())){
            throw new SystemException(AppHttpCodeEnum.PASSWORD_NOT_NULL);
        }
        //邮箱不能为空
        if(!StringUtils.hasText(user.getEmail())){
            throw new SystemException(AppHttpCodeEnum.EMAIL_NOT_NULL);
        }
        //昵称不能为空
        if(!StringUtils.hasText(user.getNickName())){
            throw new SystemException(AppHttpCodeEnum.NICKNAME_NOT_NULL);
        }
        //手机号码不能为空
        if(!StringUtils.hasText(user.getPhonenumber())){
            throw new SystemException(AppHttpCodeEnum.PHONENUMBER_NOT_NULL);
        }

        //判断用户传给我们的用户名是否在数据库中已经存在,userNameExist方法是下面自定义的
        if(UserNameExist(user.getUserName())){
            throw new SystemException(AppHttpCodeEnum.USERNAME_EXIST);
        }

        //判断昵称是不是存在
        if(NickNameExist(user.getNickName())){
            throw new SystemException(AppHttpCodeEnum.NICKNAME_EXIST);
        }

        //判断邮箱是否存在
        if(EmailExist(user.getEmail())){
            throw new SystemException(AppHttpCodeEnum.EMAIL_EXIST);
        }

        //判断电话是否存在
        if(PhoneNumberExist(user.getPhonenumber())){
            throw new SystemException(AppHttpCodeEnum.PHONENUMBER_EXIST);
        }



    }

    //验证电话是否存在
    private boolean PhoneNumberExist(String phonenumber) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhonenumber , phonenumber);
        Boolean result = count(queryWrapper) > 0;
        return result;
    }

    //验证邮箱是否存在
    private boolean EmailExist(String email) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getEmail , email);
        Boolean result = this.count(queryWrapper) > 0;
        return result;
    }

    //判断用户传给我们的昵称是否在数据库中已经存在
    private boolean NickNameExist(String nickName) {
        //要知道是否存在,首先就是要根据条件去查找在数据库中查询
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        //根据昵称作为条件查询数据
        queryWrapper.eq(User::getNickName , nickName);
        //如果大于0说明确实子啊数据库中已经查出来了,也就是说其实已经存在
        Boolean result = count(queryWrapper) > 0;
        return result;
    }

    //判断用户传给我们的用户名是否在数据库中已经存在
    private boolean UserNameExist(String userName) {
        //要知道是否存在,首先就是要根据条件去数据库查询
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        //拿用户写的用户名和数据库里面的用户名进行比较
        queryWrapper.eq(User::getUserName , userName);
        //如果大于0就说明是从数据库中查询出来了,也就是说明已经存在数据库的
        Boolean result = count(queryWrapper) > 0;
        //为True就说明存在
        return result;
    }
}
